var storage = require('electron-storage');
var url = require('url');
const electron = require('electron');
var app = electron.app;
var BrowserWindow = electron.BrowserWindow;
var Tray = electron.Tray;
var Menu = electron.Menu;
// In main process.
const {crashReporter} = require('electron')
var ipc = require('electron').ipcMain;
var DEBUG = require('./config.js').DEBUG;
//var localCrashReporter = require('electron-local-crash-reporter');

var mainWindow = null;
var appTray = null;
var forceQuit = false;//用户强制退出app


function createAppTray() {
    var iconPath = __dirname + '/images/app_icon.png';
    var appIcon = new Tray(iconPath);
    appIcon.on('click', () => {
        mainWindow.show();
    })
    if (process.platform == 'win32') {
        var contextMenu = Menu.buildFromTemplate([
            {
		label: '打开轻言', type:'normal',
		click:function() {
                    console.log("open");
                    mainWindow.show();
		},
            },
            {
		type: 'separator'
            },
            {
		label: '退出', type: 'normal',
		click:function() {
                    console.log("quit");
                    app.quit();
		},
            },
	]);
	appIcon.setContextMenu(contextMenu);
    }
    return appIcon;
}

function createMainWindow(isLogin) {
    var opts = {
        title:"轻言",
        width: 1024,
        height: 800,
        minWidth:800,
        minHeight:600,
        backgroundColor:'#ffffff',
        'web-preferences': {'web-security': true}
    };
    mainWindow = new BrowserWindow(opts);

    if (!isLogin) {
        mainWindow.loadURL('file://' + __dirname + '/login.html');
    } else {
        mainWindow.loadURL('file://' + __dirname + '/index.html');
    }
    if (DEBUG) {
        mainWindow.openDevTools();
    }

    mainWindow.on('closed', function() {
        mainWindow = null;
    });
    mainWindow.on('close', function(event) {
        console.log("close event:", event);
        if (!forceQuit) {
            mainWindow.hide();
            event.preventDefault();
        }
    });
}



function main() {
    var shouldQuit = app.makeSingleInstance(function(commandLine, workingDirectory) {
        if (mainWindow) {
            mainWindow.show();
        }
    });

    if (shouldQuit) {
        app.quit();
        return;
    }

    // Quit when all windows are closed.
    app.on('window-all-closed', function() {
        if (process.platform != 'darwin') {
            app.quit();
        }
    });

    app.on("activate", function(event, hasVisibleWindows) {
        console.log("app activate:" + hasVisibleWindows);
        if (!mainWindow) {
            storage.get("token.json")
                   .then(data => {
                       console.log("token:", data);
                       if (data.accessToken) {
                           createMainWindow(true);
                       } else {
                           createMainWindow(false);
                       }
                   }).catch(err => {
                       console.error(err);
                       createMainWindow(false);
                   });
        }
    });

    if (DEBUG) {
        if (process.argv.length == 3 && process.argv[2] == "test") {
            app.setPath("userData", "/Users/houxh/Library/Application Support/轻言dev");
        }
    }
    console.log("exec path:" + process.execPath);
    console.log("user data path:" + app.getPath("userData"));
    console.log("app path:" + app.getAppPath());
    console.log("temp path:", app.getPath("temp"));


    ipc.on('set-badge', function(event, arg) {
        if (process.platform == 'darwin') {
            app.dock.setBadge(arg);
        }
        event.returnValue = "ok";
    });

    ipc.on('exit', function(event, arg) {
        console.log(event, arg);
        mainWindow.webContents.send("exit");
    });



    app.on('activate', function(event) {
        //osx only
        console.log("app activate event:", event);
        mainWindow.show();
    });

    app.on('before-quit', function() {
        forceQuit = true;
        console.log("app before quit event, use force quit app")
    });

    app.on('ready', function() {
        crashReporter.start({submitURL: '',
                uploadToServer: false,
                companyName: '木瓜科技'
        });

        console.log("last crash:", crashReporter.getLastCrashReport());
        console.log("uploaded reports:", crashReporter.getUploadedReports());

        appTray = createAppTray();
        if (process.platform == 'darwin' && !DEBUG) {
            //enable copy shortcut
            var name = app.getName();
            var template = [
                {
                    label: name,
                    submenu: [
                        {label: "剪切", accelerator: "CmdOrCtrl+X", selector: "cut:" },
                        {label: "复制", accelerator: "CmdOrCtrl+C", selector: "copy:"},
                        {label: "粘贴", accelerator: "CmdOrCtrl+V", selector: "paste:"},
                        {type: "separator"},
                        {
                            label: '退出',
                            accelerator: 'Command+Q',
                            click: function () {
                                app.quit();
                            }
                        }
                    ]
                },
            ];
            menu = Menu.buildFromTemplate(template);
            Menu.setApplicationMenu(menu);
        }

        storage.get("token.json")
               .then(data => {
                   console.log("token:", data);
                   if (data.accessToken) {
                       createMainWindow(true);
                   } else {
                       createMainWindow(false);
                   }
               }).catch(err => {
                   console.error(err);
                   createMainWindow(false);
               });
    });
}


main();
